package me.yobol.blog.service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import me.yobol.blog.bean.PermissionBean;
import me.yobol.blog.bean.UserBean;
import me.yobol.blog.commons.LoginStatus;
import me.yobol.blog.dao.IPermissionDAO;
import me.yobol.blog.dao.IUserDAO;
import me.yobol.blog.dao.impl.PermissionDAOImpl;
import me.yobol.blog.dao.impl.UserDAOImpl;
import me.yobol.blog.exception.PasswordNotTrueException;
import me.yobol.blog.exception.UserNameDuplicationException;
import me.yobol.blog.exception.UserNameNotFoundException;
import me.yobol.blog.util.sql.ConnectionFactory;

public class UserService {
	
	private static IUserDAO udi = new UserDAOImpl();
	private static IPermissionDAO pdi = new PermissionDAOImpl();
	private static Connection ctn = ConnectionFactory.getInstance().getConnection();
	
	/**
	 * 用户注册
	 * @param user
	 * @throws UserNameDuplicationException 
	 */
	public static boolean register(UserBean user) throws UserNameDuplicationException{
		
		String name = user.getName();
		
		List<UserBean> users = null;
		try {
			users = udi.getByName(ctn, name);
			
			if(users.size() > 0){
				System.out.println("-------- 该用户名已存在 --------");
				throw new UserNameDuplicationException();
			}

			int userId = udi.save(ctn, user);
			//为用户赋予默认访问权限——user
			if (userId > 0) {
				pdi.save(ctn, new PermissionBean(userId,LoginStatus.USER));
			}
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return false;
	}
	
	public static boolean loginIn(UserBean user) throws UserNameNotFoundException, PasswordNotTrueException{
		String name = user.getName();
		String password = user.getPassword();
		
		List<UserBean> users = null;
		
		try {
			users = udi.getByName(ctn, name);
			
			if(users.size() == 0){
				System.out.println("-------- 该用户名不存在 --------");
				throw new UserNameNotFoundException();
			}
			
			//取得登录用户的账户信息
			UserBean u = users.get(0);
			if(!u.getPassword().equals(password)){
				System.out.println("-------- 密码不正确 --------");
				throw new PasswordNotTrueException();
			}
			
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return false;
	}
}
